﻿using System;
using System.Collections.Generic;
using System.Web.UI;

using Carbon.Web.Forms.Extensions;
using Carbon.Web.Forms.Collections;

namespace Carbon.Web.Forms.Controls
{
    [ParseChildren(false)]
    [PersistChildren(true)]
    public abstract class DataContextControl<TViewModel> : UserControl, IDataProxy, IDataContextControl, IViewControl
    {
        #region Fields (8)
        private List<IDataContextControl> m_ChildDataContextControls = default(List<IDataContextControl>);

        private int m_HowManyViewStatesNeedToBeLoaded = default(int);

        #endregion

        #region Events (1)
        public event ViewStateLoadedDelegate ViewStateLoaded;
        #endregion

        #region Properties (7)

        protected List<IDataContextControl> ChildDataContextControls
        {
            get
            {
                if (m_ChildDataContextControls == null)
                    m_ChildDataContextControls = new List<IDataContextControl>();
                return m_ChildDataContextControls;
            }
        }
        private int HowManyViewStatesNeedToBeLoaded
        {
            get
            {
                return m_HowManyViewStatesNeedToBeLoaded;
            }
            set
            {
                m_HowManyViewStatesNeedToBeLoaded = value;
            }
        }
        public object DataContext
        {
            get
            {
                return ViewModel;
            }
        }

        public IDataContextControl OwnerDataContextControl
        {
            get
            {
                return this.GetParentControlOrNull<IDataContextControl>();
            }
        }

        public bool PipelineEnabled
        {
            get
            {
                Object cachedPipelineEnabled = ViewState["PipelineEnabled"];

                if (cachedPipelineEnabled == null)
                {
                    return true;
                }

                return (bool)cachedPipelineEnabled;
            }
            set
            {
                this.TrackViewState();
                ViewState["PipelineEnabled"] = value;
            }
        }

        protected bool ViewModelLoaded
        {
            get
            {
                return ViewState["ViewModel"] != null;
            }
        }

        public TViewModel ViewModel
        {
            get
            {
                TViewModel model = (TViewModel)ViewState["ViewModel"];

                if (model == null)
                {
                    model = CreateViewModel();
                    ConnectViewModel(model);
                    ViewState["ViewModel"] = model;
                }

                return model;
            }
            set
            {
                if (ViewState["ViewModel"] != null)
                    throw new InvalidOperationException("Model is already calculated, unexplained error occured.");

                ConnectViewModel(value);

                ViewState["ViewModel"] = value;
            }
        }

        /// <summary>
        /// Does not wait for loadview state and does not return values to model
        /// </summary>
        public bool InitialExecutionMode
        {
            get
            {
                Object cachedInitialExecutionModeObject = ViewState["InitialExecutionMode"];

                if (cachedInitialExecutionModeObject == null)
                {
                    return true;
                }

                return (bool)cachedInitialExecutionModeObject;
            }
            set
            {
                this.TrackViewState();
                ViewState["InitialExecutionMode"] = value;
            }
        }
        #endregion

        #region ASP Processing

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            EnsureChildControls();
        }

        private bool m_DidUpdateControl = default(bool);
        private bool DidUpdateControl
        {
            get
            {
                return m_DidUpdateControl;
            }
            set
            {
                m_DidUpdateControl = value;
            }
        }

        protected override void LoadViewState(object savedState)
        {
            ViewControlUpdateState.OnLoadViewState(savedState, base.LoadViewState);

            if (ViewModelLoaded)
                ConnectViewModel(ViewModel);

            FireControlDataBind(UpdateControlStageEnum.RestoreState);

            OnViewStateLoaded(this, ViewStateLoadedEventArgs.Empty);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if ((HowManyViewStatesNeedToBeLoaded == 0) == false) throw new InvalidOperationException("(HowManyViewStatesNeedToBeLoaded == 0) == false");

            if (!InitialExecutionMode)
            {
                if (PipelineEnabled && !DidUpdateControl)
                    throw new InvalidOperationException("Control needed to be updated.");

                FireModelDataBind();
            }
        }

        private void FireModelDataBind()
        {
            if (!PipelineEnabled)
                return;

            DataBindValuesToModel(this, this);

            DidUpdateControl = true;
        }


        #endregion

        #region Methods (8)

        protected abstract TViewModel CreateViewModel();

        private ViewControlUpdateState m_PipelineState = default(ViewControlUpdateState);
        public ViewControlUpdateState PipelineState
        {
            get
            {
                return m_PipelineState;
            }
            set
            {
                m_PipelineState = value;
            }
        } 

        private void DataBindValuesToControls(Control root, UpdateControlStageEnum stage, Control current, List<EventHandler<ChildViewControlPreUpdateEventArgs>> childHandlers)
        {
            PipelineState = new ViewControlUpdateState();
            PipelineState.PreUpdateEventHandlers = new List<EventHandler<ChildViewControlPreUpdateEventArgs>>();
            PipelineState.Stage = stage;

            UpdateControlEventArgs args = new UpdateControlEventArgs(stage, PipelineState.PreUpdateEventHandlers);

            OnUpdateControl(this, args);

            PipelineState.ControlDescendantsUpdated = args.ControlDescendantsUpdated;
        }

        private void DataBindValuesToModel(Control root, Control current)
        {
            if (current is IBlackBoxBarrier)
                return;

            try
            {
                if (current is IViewControl)
                {
                    IViewControl viewControl = (IViewControl)current;

                    UpdateModelEventArgs args = new UpdateModelEventArgs();
                    viewControl.OnUpdateModel(root, args);
                }

                foreach (Control c in current.Controls)
                {
                    DataBindValuesToModel(root, c);
                }
            }
            finally
            {
                
            }
        }


        public override void Dispose()
        {
            base.Dispose();

            if (ViewModelLoaded && ViewModel is IDisposable)
            {
                ((IDisposable)ViewModel).Dispose();
            }
        }

        private void FireControlDataBind(UpdateControlStageEnum stage)
        {
            if (!PipelineEnabled)
                return;

            List<EventHandler<ChildViewControlPreUpdateEventArgs>> handlers = new List<EventHandler<ChildViewControlPreUpdateEventArgs>>();
            DataBindValuesToControls(this, stage, this, handlers);
        }

        /// <summary>
        /// This is a hook that enables to connect any non persistable external connections to ViewModel before it's being used
        /// </summary>
        /// <param name="model"></param>
        protected virtual void ConnectViewModel(TViewModel model)
        {
        }

        public void ForceSetViewModel(TViewModel model)
        {
            ConnectViewModel(model);
            ViewState["ViewModel"] = model;
        }

        protected virtual void OnViewStateLoaded(object sender, ViewStateLoadedEventArgs args)
        {
            if (ViewStateLoaded != null)
                ViewStateLoaded(sender, args);
        }

        public void RegisterChildDataContextControl(IDataContextControl dependantControl)
        {
            ChildDataContextControls.Add(dependantControl);
            dependantControl.ViewStateLoaded += new ViewStateLoadedDelegate(dependantControl_ViewStateLoaded);
            HowManyViewStatesNeedToBeLoaded++;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            FireControlDataBind(UpdateControlStageEnum.Render);

            this.Page.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
        }

        void Page_PreRenderComplete(object sender, EventArgs e)
        {
            DataBind();
        }

        protected override object SaveViewState()
        {
            InitialExecutionMode = false;
            return ViewControlUpdateState.OnSaveViewState(base.SaveViewState);
        }
        #endregion

        #region Event Handlers (1)

        void dependantControl_ViewStateLoaded(object sender, ViewStateLoadedEventArgs args)
        {
            if ((HowManyViewStatesNeedToBeLoaded > 0) == false) throw new InvalidOperationException("(HowManyViewStatesNeedToBeLoaded > 0) == false");
            HowManyViewStatesNeedToBeLoaded--;

            if (HowManyViewStatesNeedToBeLoaded == 0)
                FireControlDataBind(UpdateControlStageEnum.RestoreState);
        }

        #endregion

        public virtual void OnUpdateControl(object sender, UpdateControlEventArgs args)
        {
            DidUpdateControl = true;

        }

        public virtual void OnUpdateModel(object sender, UpdateModelEventArgs args)
        {

        }
    }
}
